import {replaceByObj} from './xUtil.js'
import{findParentsCodeByRc,hiberarchyToTree} from './treeUtil.js';
import cell from "./cell.js";


const tmplMenuUl = '<ul class="{{ulClass}}" >{{ulHtml}}</ul>';
const tmplMenuLi = '<li data-code="{{code}}">{{item}}{{liHtml}}</li> ';


export default class menu {
	// 定义变量
	$root;
	//所以的上级 包括自己;
	vActiveCode = [];
	vMenuData = null;
	vCfg;

	constructor(cfg) {
	    this.vCfg =cfg;
		this.vMenuData = hiberarchyToTree(cfg.data);
        this.vMenuData = cfg.data;
        this.setAllActive(cfg.active);
		this.$root = $('#' + cfg.el);
		this.render();
	}

	setAllActive(code) {
		let p = findParentsCodeByRc(this.vMenuData,code);
		p.reverse();
		this.vActiveCode = [...p];
		this.vActiveCode.push(code);
	}

	render(){
        this.$root.html(this.renderMenu());
    }

	renderMenu() {
		let _this = this;
        let group ='';

        function renderLi(item,level){
            let isActive = _this.vActiveCode.includes(item.code)?true:false;
            let html= cell.renderMenuCell({
                style: isActive?"active":'' ,
                code :item.code,
                data:item.name,
                icon:item.icon,
                level,
                badge:item.badge,
                link:isActive?'#':item.link,
                hasChildren:item.children?true:false
            });
            /*let style =  isActive?'active':'';
            style = item.children? (style+' has-submenu'):style;*/
            return replaceByObj(tmplMenuLi,{item:html,liClass:'nav-item'});
        }

		function renderUl(items,parent,level) {
			let ulHtml = '';
			for(let o of items) {
                let liHtml = '';
                if(level ==1 && _this.vCfg.group && o.group != group){
                    liHtml += cell.renderLabel({label:o.group});
                    group = o.group;
                }
				liHtml += renderLi(o,level);
                //递归处理子的
				if(o.children) {
					liHtml = liHtml.replace('{{liHtml}}', renderUl(o.children,o,level+1));
				}else 
				    liHtml = liHtml.replace('{{liHtml}}','');
				ulHtml += liHtml;
			}
			let ulClass = parent? 'dropdown-menu':'navbar-nav m-auto';

			return replaceByObj(tmplMenuUl,{ulClass,ulHtml});
		}

		return renderUl(this.vMenuData,null,1);
	}

}